import time
from pynput import keyboard
from threading import Thread, Event
from utils import move_and_click, save_log, check_color, set_stop_event
from option import find_options
from settings import sleep_options

# 控制事件 - 为两种操作分别创建控制变量
stop_he_event = Event()    # 控制"和了"操作
stop_pack_event = Event()  # 控制"开包"操作
running_he = False         # "和了"运行状态
running_pack = False       # "开包"运行状态

stop_event = Event()
# 将 stop_event 传递给 utils.py
set_stop_event(stop_event)

def on_press(key):
    """键盘按键按下事件处理"""
    global running_he, running_pack
    try:
        # 按下w键切换"和了"循环状态（开始/停止）
        if key.char == 'w':
            if not running_he:
                running_he = True
                print("开始和了循环...")
                stop_he_event.clear()
            else:
                running_he = False
                print("停止和了循环...")
                stop_he_event.set()

        # 按下e键切换"开包"循环状态（开始/停止）
        elif key.char == 'e':
            if not running_pack:
                running_pack = True
                print("开始开包循环...")
                stop_pack_event.clear()
            else:
                running_pack = False
                print("停止开包循环...")
                stop_pack_event.set()

        # 按下q键退出程序
        elif key.char == 'q':
            print("退出程序...")
            # 停止所有运行中的操作
            running_he = False
            running_pack = False
            stop_he_event.set()
            stop_pack_event.set()
            stop_event.set()
            return False  # 停止监听

    except AttributeError:
        pass

def loop_he():
    """循环执行"和了"操作"""
    while running_he and not stop_he_event.is_set():
        move_and_click("和了", 0.2)
        # 可以根据需要调整循环间隔
        # time.sleep(0.05)

def loop_pack():
    """循环执行"开包找生命"操作"""
    global running_pack
    while running_pack and not stop_pack_event.is_set():
        # 调用find_shengming函数
        result = find_shengming()
        if result != 0:
            print(f"开包找生命操作结束，结果代码: {result}")
            # 如果find_shengming返回非0结果，自动停止操作
            running_pack = False
        # 可以根据需要添加间隔时间
        # time.sleep(1)

def find_shengming():
    """
    开包 找生命，加入running_pack状态控制
    """
    for _ in range(20):
        # 每次循环开始检查是否需要停止
        if not running_pack or stop_pack_event.is_set():
            print("检测到停止信号，退出开包找生命循环")
            return 0

        gold_array = [1, 2, 3, 4, 5]
        is_sell = False
        for gold_index in gold_array:
            # 每个包操作前也检查一次状态
            if not running_pack or stop_pack_event.is_set():
                print("检测到停止信号，退出当前包操作")
                return 0

            button_name1 = f"第{gold_index}个包"
            button_name2 = f"第{gold_index}个包开启"
            move_and_click(button_name1)
            save_log("开金包")
            move_and_click(button_name2)
            time.sleep(sleep_options["找万象"])
            shengming_index, value = select_option()
            if value == 9999:
                return 1
            elif value == 0:
                return 1
            else:
                option_name = f"里面的第{shengming_index}个选择"
                move_and_click(option_name, 0)
                if not value == 999:
                    move_and_click("最右边护符", sleep_options["最右边护符"])
                    move_and_click("出售")
        if not is_sell:
            is_money2 = check_color("刷新商品", (85, 111, 212), sleep_options["最右边护符"])
            if is_money2:
                move_and_click("刷新商品")
                move_and_click("弹框确认")
            else:
                # 刷新没钱
                return 0
    return 0

def calculate_value(package):
    """
    根据包的属性计算其综合价值
    生命9999
    膨胀0
    镀金
    幸福30
    升级卡0
    瓶子999
    """
    # 确保包包含必要的属性
    if not all(key in package for key in ['value', 'seal', 'name']):
        return 0

    if package['seal'] == "shengming":
        return 9999
    if package['seal'] == "pengzhang":
        return 0
    if package['name'] is None:
        if package['seal'] == "dujin":
            if package['value'] == 1:
                return 18
            elif package['value'] == 2:
                return 27
            else:
                return 36
        elif package['seal'] == "xingfu":
            return 30
        else:
            if package['value'] == 1:
                return 6
            elif package['value'] == 2:
                return 9
            else:
                return 12
    else:
        if package['name'] in ["yunduo", "yunduo_p"]:
            return 999
        else:
            #升级卡不选
            return 0

def select_option():
    """
    选包：找出价值最大的包并返回其下标和价值
    """
    packages_info = find_options()
#     print(packages_info)

    # 计算每个包的综合价值
    values = [calculate_value(pkg) for pkg in packages_info]
#     print(values)

    # 找到最大价值的下标和对应价值
    max_value = max(values)
    max_index = values.index(max_value)

    return max_index + 1, max_value



if __name__ == "__main__":
    print("程序已启动...")
    print("按 'w' 开始/停止和了操作")
    print("按 'e' 开始/停止开包操作")
    print("按 'q' 退出程序")

    # 启动键盘监听器
    listener = keyboard.Listener(on_press=on_press)
    listener.start()

    try:
        # 用于跟踪当前运行的线程
        he_thread = None
        pack_thread = None

        while True:
            # 处理"和了"线程
            if running_he and (he_thread is None or not he_thread.is_alive()):
                he_thread = Thread(target=loop_he)
                he_thread.start()

            # 处理"开包"线程
            if running_pack and (pack_thread is None or not pack_thread.is_alive()):
                pack_thread = Thread(target=loop_pack)
                pack_thread.start()

            time.sleep(0.1)
    except KeyboardInterrupt:
        print("程序被手动中断")
    finally:
        # 确保所有线程都已停止
        running_he = False
        running_pack = False
        stop_he_event.set()
        stop_pack_event.set()
        listener.stop()
        print("程序已退出")

# if __name__ == "__main__":
#     name = select_option()
#     print(name)
